﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RestAPIDemo.Models;
using Newtonsoft;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.IO;
using Microsoft.AspNetCore.Http;

namespace RestAPIDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        static P p = new P(-1, "");
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet("/company/List")]
        public ActionResult<WeatherForecast> GetTxt(string id)
        {
            if (id.Equals("1"))
                return new WeatherForecast()
                {
                    Summary = "1"
                };
            else
            {
                var rng = new Random();
                return new WeatherForecast()
                {
                    Summary = "2"
                };
            } 
        }

        // query 表单入参
        [HttpGet("company/List")]
        public JsonResult GetPrintingHouseGroup(int state, int page, int count, string name = "")
        {
            // 假数据
            List<PrintingHouse> printingHouses = new List<PrintingHouse>();
            printingHouses.Add(new PrintingHouse()
            {
                id = "1",
                company_name = "印厂1",
                contact_user = "联系人1",
                contact_phone = "12312312311",
                username = "1",
                state = 1,
                lastDate = DateTime.Now.ToString()
            });
            printingHouses.Add(new PrintingHouse()
            {
                id = "2",
                company_name = "印厂2",
                contact_user = "联系人2",
                contact_phone = "12312312311",
                username = "2",
                state = 0
            });
            // 返回数据
            if (state == -1)
                return new JsonResult(printingHouses.Where(t => t.company_name.Contains(name)).ToList());
            else
                return new JsonResult(printingHouses.Where(t => t.state == state && t.company_name.Contains(name)).ToList());
        }

        // query 表单入参
        [HttpPost("company/List")]
        public ActionResult<IEnumerable<PrintingHouse>> PostPrintingHouseGroup(int state, int page, int count, string name = "")
        {
            // 假数据
            List<PrintingHouse> printingHouses = new List<PrintingHouse>();
            printingHouses.Add(new PrintingHouse()
            {
                id = "1",
                company_name = "印厂1",
                contact_user = "联系人1",
                contact_phone = "12312312311",
                username = "1",
                state = 1,
                lastDate = DateTime.Now.ToString()
            });
            printingHouses.Add(new PrintingHouse()
            {
                id = "2",
                company_name = "印厂2",
                contact_user = "联系人2",
                contact_phone = "12312312311",
                username = "2",
                state = 0
            });
            // 返回数据
            if (state == -1)
                return printingHouses.Where(t => t.company_name.Contains(name)).ToList();
            else
                return printingHouses.Where(t => t.state == state && t.company_name.Contains(name)).ToList();
        }

        // query Json入参
        [HttpPost("company/List2")]
        public JsonResult GetPrintingHouseGroup([FromBody]P p)
        {
            // 假数据
            List<PrintingHouse> printingHouses = new List<PrintingHouse>();
            printingHouses.Add(new PrintingHouse()
            {
                id = "1",
                company_name = "印厂1",
                contact_user = "联系人1",
                contact_phone = "12312312311",
                username = "1",
                state = 1,
                lastDate = DateTime.Now.ToString()
            });
            printingHouses.Add(new PrintingHouse()
            {
                id = "2",
                company_name = "印厂2",
                contact_user = "联系人2",
                contact_phone = "12312312311",
                username = "2",
                state = 0
            });
            // 返回数据
            //JObject j = (JObject)JsonConvert.DeserializeObject(jsonPara);
            //int state = int.Parse(j["state"].ToString());
            //string name = j["name"].ToString();
            //if (state == -1)
            //    return new JsonResult(printingHouses.Where(t => t.company_name.Contains(name)).ToList());
            //else
            //    return new JsonResult(printingHouses.Where(t => t.state == state && t.company_name.Contains(name)).ToList());
            return new JsonResult(printingHouses.ToList());
        }

        // 多文件上传
        [HttpPost("Photos")]
        public async Task<IActionResult> UploadPhotosAsync([FromForm]IFormFileCollection files)
        {
            long size = files.Sum(f => f.Length);
            var fileFolder = @"C:\Users\Administrator\Desktop";
            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                                   Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(fileFolder, fileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
            }

            return Ok(new { count = files.Count, size });
        }

        // 多文件上传 + 表单入参
        [HttpPost("Photos2")]
        public async Task<IActionResult> UploadPhotosAsync([FromForm]F f)
        {
            long size = f.files.Sum(f => f.Length);
            var fileFolder = @"C:\Users\Administrator\Desktop";
            foreach (var file in f.files)
            {
                if (file.Length > 0)
                {
                    var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                                   Path.GetExtension(file.FileName);
                    var filePath = Path.Combine(fileFolder, fileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
            }

            return Ok(new { count = f.files.Count, size });
        }
    }


    public class F
    {
        public string id { get; set; }
        public string fsName { get; set; }
        public string uploadTime { get; set; }
        public IFormFileCollection files { get; set; }
    }


    public class P
    {
        public P(int state, string name)
        {
            this.state = state;
            this.name = name;
        }
        public int state { get; set; }
        public string name { get; set; }
    }
}
